<template>
  <div class="calendar">
    <div class="weekdays weeks">
      <div v-for="day in weekdays" :key="day" class="week-item">
        <div class="cn">{{ day.cn }}</div>
        <div class="en">{{ day.en }}</div>
      </div>
    </div>
    <div class="weeks">
      <div
        v-for="(week, weekIndex) in weeksInMonth"
        :key="weekIndex"
        class="week"
      >
        <div
          v-for="(day, dayIndex) in week"
          :key="dayIndex"
          class="day-item"
          :class="{
            'not-current': day === 0,
            'special-day': isSpecialDay(dayIndex),
            'selected-day': selectedDate == displayMonth + '-' + day
          }"
          @click="selectDay(day, dayIndex)"
        >
          {{ day || '' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, defineEmits, onMounted } from 'vue'

const props = defineProps({
  specialDays: Array,
  selectedDate: String,
  displayMonth: {
    type: String,
    default: () => {
      const today = new Date()
      return `${today.getFullYear()}-${today.getMonth() + 1}`
    }
  }
})

const emit = defineEmits(['update:selectedDate'])
const weekdays = ref([
  {
    cn: '周日',
    en: 'Sun'
  },
  {
    cn: '周一',
    en: 'Mon'
  },
  {
    cn: '周二',
    en: 'Tue'
  },
  {
    cn: '周三',
    en: 'Wed'
  },
  {
    cn: '周四',
    en: 'Thu'
  },
  {
    cn: '周五',
    en: 'Fri'
  },
  {
    cn: '周六',
    en: 'Sat'
  }
])
const year = ref('')
const month = ref('')

const formattedDisplayMonth = computed(() => {
  return `${year.value}年${parseInt(month.value, 10) + 1}月`
})

const daysInMonth = computed(() => {
  const date = new Date(
    parseInt(year.value, 10),
    parseInt(month.value, 10) + 1,
    0
  )
  return Array.from({ length: date.getDate() }, (_, i) => i + 1)
})

const firstDayOfMonth = computed(() => {
  const date = new Date(parseInt(year.value, 10), parseInt(month.value, 10), 1)
  return date.getDay()
})

const weeksInMonth = computed(() => {
  const days = daysInMonth.value
  const firstDay = firstDayOfMonth.value
  const weeks = []
  let week = []

  for (let i = 0; i < firstDay; i++) {
    week.push(0)
  }

  days.forEach((day) => {
    week.push(day)
    if (week.length === 7) {
      weeks.push(week)
      week = []
    }
  })

  if (week.length > 0) {
    while (week.length < 7) {
      week.push(0)
    }
    weeks.push(week)
  }

  return weeks
})

const isSelected = computed(() => (day: number) => {
  console.log('传进来的日期:L', day)
  if (!props.selectedDate) return false
  const [getFullYear, getMonth, getDate] = props.selectedDate
    .split('-')
    .map(Number)
  console.log(day, getDate)
  console.log(parseInt(year.value, 10), getFullYear)
  console.log(parseInt(month.value, 10), getMonth - 1)
  let selected =
    day === getDate &&
    parseInt(year.value, 10) === getFullYear &&
    parseInt(month.value, 10) === getMonth - 1
  console.log('是否选中', selected)
  return selected
})

const isSpecialDay = (dayIndex: number) => {
  return dayIndex === 1 // 每周一为特殊日期
}

const selectDay = (day: number, dayIndex: number) => {
  if (canSelectDay(day, dayIndex)) {
    console.log('可以选中')
    emit(
      'update:selectedDate',
      `${year.value}-${
        parseInt(month.value) >= 9
          ? parseInt(month.value) + 1
          : '0' + (parseInt(month.value) + 1)
      }-${day}`
    )
  }
}

const initDate = () => {
  const [getFullYear, getMonth] = props.displayMonth.split('-').map(Number)
  console.log('初始话', getFullYear, getMonth)
  year.value = getFullYear.toString()
  month.value = (getMonth - 1).toString() // 减去 1 来得到正确的月份值

  const today = new Date()
  const todayYear = today.getFullYear()
  const todayMonth = today.getMonth()
  const todayDate = today.getDate()
  console.log('初始话年月日', todayYear, todayMonth, todayDate)
  if (!props.selectedDate) {
    if (todayYear === getFullYear && todayMonth === getMonth - 1) {
      console.log('这个地方？')
      emit(
        'update:selectedDate',
        `${todayYear}-${
          todayMonth >= 9 ? todayMonth + 1 : '0' + (todayMonth + 1)
        }-${todayDate}`
      )
    } else {
      const defaultDate = new Date(getFullYear, getMonth - 1, 1)
      emit(
        'update:selectedDate',
        `${defaultDate.getFullYear()}-${
          defaultDate.getMonth() >= 9
            ? defaultDate.getMonth() + 1
            : '0' + (defaultDate.getMonth() + 1)
        }-${defaultDate.getDate()}`
      )
    }
  }
}
const canSelectDay = (day, dayIndex) => {
  console.log('当前选中的日期', day, dayIndex)
  console.log('是否特殊日期', !isSpecialDay(dayIndex))
  return day !== 0 && !isSpecialDay(dayIndex)
}

onMounted(() => {
  initDate()
})
</script>

<style scoped lang="scss">
.calendar {
  width: 670rpx;
  margin: 0 auto;
  text-align: center;
  padding-bottom: 10rpx;
}
.header {
  margin-bottom: 10px;
}
.weekdays,
.weeks {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}
.weekdays {
  margin-bottom: 30rpx;
  .week-item {
    width: 64rpx;
    margin-right: 34rpx;
    text-align: left;
    &:last-child {
      margin-right: 0;
    }
  }
}
.week {
  display: contents; /* 使子元素直接成为 grid 的一部分 */
  .day-item {
    text-align: left;
    width: 64rpx;
    margin-bottom: 20rpx;
    margin-right: 34rpx;
    &:last-child {
      margin-right: 0;
    }
  }
}
.days div,
.week div {
  cursor: pointer;
}
.not-current {
  color: #ccc;
}
.special-day {
  color: rgba(255, 255, 255, 0.5);
  border-radius: 50%;
  pointer-events: none; /* 特殊日期不可点击 */
}
.selected-day {
  color: white;
  text-decoration: underline;
}
</style>
